#include "board_bsp.h"
#include "main.h"
#include "stdbool.h"
#include "stdio.h"
#include "ring_buffer.h"
#include "usart.h"
#include "shell.h"
#include "string.h"
#include "stdarg.h"

uint8_t rxMain;
uint8_t rbMainBuffer[256];
ring_buffer_t rbMain;

// 主板485通讯
bool rs485Init(void)
{
    bool ret = true;
    ret = rb_init(&rbMain, rbMainBuffer, sizeof(rbMainBuffer));
    if(ret == false)
    {
        printf("rs485Init: ring buffer init error\r\n");
        return false;
    }
    // 启动串口接收
    if(HAL_UART_Receive_IT(&huart1, (uint8_t*)&rxMain, 1) != HAL_OK)
    {
        printf("rs485Init: huart1 receive it error\r\n");
        return false;
    }
    HAL_GPIO_WritePin(RS485_WR_GPIO_Port, RS485_WR_Pin, GPIO_PIN_RESET);

    return true;
} 

// 主动下发数据
void rs485Write(uint8_t *data, uint16_t len)
{
    HAL_GPIO_WritePin(RS485_WR_GPIO_Port, RS485_WR_Pin, GPIO_PIN_SET);
    HAL_UART_Transmit(&huart1, data, len, 1000);
    HAL_GPIO_WritePin(RS485_WR_GPIO_Port, RS485_WR_Pin, GPIO_PIN_RESET);
}

int rs485Read(uint8_t *data, uint16_t len)
{
   return rb_read(&rbMain, data, len);
}

void rs485Rst(void)
{
    rb_reset(&rbMain);
}

// SHELL
uint8_t rxShell;
uint8_t rbShellBuffer[256];
ring_buffer_t rbShell;
Shell shell;
char shellBuffer[512];

short shellRead(char *data, unsigned short len)
{
    return rb_read(&rbShell, (uint8_t*)data, len);
}

short shellWrite(char *data, unsigned short len)
{
    
    HAL_UART_Transmit(&huart2, (uint8_t*)data, len, 1000);
    return len;
}

void Shell_Init(void)
{
    rb_init(&rbShell, rbShellBuffer, sizeof(rbShellBuffer));
    shellInit(&shell, shellBuffer, sizeof(shellBuffer));
    shell.read = shellRead;
    shell.write = shellWrite;
    HAL_UART_Receive_IT(&huart2, (uint8_t*)&rxShell, 1);
}

int fputc(int c, FILE * f)
{
    HAL_UART_Transmit(&huart2, (uint8_t*)&c, 1, 1000);
		return c;
}



